//
//  RecommendVC.swift
//  DoctorVisits
//
//  Created by lanou3g on 16/2/29.
//  Copyright © 2016年 SHH. All rights reserved.
//

import UIKit

class RecommendVC: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    
    var layout:UICollectionViewFlowLayout!
    var collectionView:UICollectionView!
    //屏幕的宽和高
    let width = UIScreen.mainScreen().bounds.width
    let height = UIScreen.mainScreen().bounds.height
    var rotateArray = Array<RotateModel>()
    
    let urlString = "http://api.le123.com/kuaikan/apipage_json.so?lc=863846020193282&city=CN_1_5_1&code=346e5b9d1bd97036&page=page_index&uuid=bd221acf-19f7-35c1-90bd-3ef197d4ce09&version=1.7.3&platform=Le123Plat0021&plattype=aphone"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载UICollectionView
        loadCollectionView()
        
        //请求数据
        //        SHHDataHelper.shareInstance.requestAllModelWithUrlString("http://api.le123.com/kuaikan/apipage_json.so?lc=863846020193282&city=CN_1_5_1&code=346e5b9d1bd97036&page=page_index&uuid=bd221acf-19f7-35c1-90bd-3ef197d4ce09&version=1.7.3&platform=Le123Plat0021&plattype=aphone")
        
        SHHDataHelper.shareInstance.requestAllRecnameWithUrlString(urlString) { (array:Array<TitleModel>) -> Void in
            
            print("====\(array[5].vt)")
            
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.collectionView.reloadData()
            })
        }
        
    }
    
    func loadCollectionView(){
        //定义collectionView的布局类型，流布局
        layout = UICollectionViewFlowLayout()
        //设置cell的大小
        layout.itemSize = CGSize(width: width/2, height: height/3)
        //滑动方向 默认方向是垂直
        layout.scrollDirection = .Vertical
        //每个Item之间最小的间距
        layout.minimumInteritemSpacing = 0
        //每行之间最小的间距
        layout.minimumLineSpacing = 0
        //设置每个item之间的间距
        layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5)
        //定义一个UICollectionView
        collectionView = UICollectionView(frame: CGRectMake(0,0,width,height), collectionViewLayout: layout)
        //设置collectionView的背景颜色
        collectionView.backgroundColor = UIColor.groupTableViewBackgroundColor()
        
        //设置collectionView的代理和数据源
        collectionView.delegate = self
        collectionView.dataSource = self
        //CollectionViewCell的注册
        collectionView.registerNib(UINib(nibName: "SHHRecommendCell", bundle: nil), forCellWithReuseIdentifier: "Cell")
        
        //设置collectionView的偏移量
        collectionView.contentInset = UIEdgeInsetsMake(height*0.3, 0, 0, 0)
        //设置表头视图:轮播图
        let scrollVC = SHHScrollVC()
        scrollVC.view.frame = CGRectMake(0, -height*0.3, width, height*0.3)
        self.addChildViewController(scrollVC)
        collectionView.addSubview(scrollVC.view)
        
//        let imageView = UIImageView(image: UIImage(named: "picholder"))
//        imageView.frame = CGRectMake(0, -height*0.3, width, height*0.3)
//        collectionView.addSubview(imageView)
        //header的注册
        collectionView.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headView")
        
        self.view.addSubview(collectionView)
    }
    
    
    
    /**
     - 该方法是可选方法，默认为1
     - returns: CollectionView中section的个数
     */
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return SHHDataHelper.shareInstance.titleAndMovieArray.count
    }
    
    /**
     - returns: Section中Item的个数
     */
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return SHHDataHelper.shareInstance.titleAndMovieArray[section].movie!.count
    }
    
    /**
     - returns: 绘制collectionView的cell
     */
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! SHHRecommendCell
        
//        cell.ImageView.image = UIImage(named: "picholder")
        
        //布局不同，图片也会不同，所以根据图片的类型进行布局，然后加载图片
        if SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].movie![indexPath.row].pich! == "" {
            cell.ImageView.sd_setImageWithURL(NSURL(string: SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].movie![indexPath.row].pic!), placeholderImage: UIImage(named: "picholder"))
        }else{
            cell.ImageView.sd_setImageWithURL(NSURL(string: SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].movie![indexPath.row].pich!), placeholderImage: UIImage(named: "picholder"))
        }
        
        //根据总集数判断是电影还是电视剧，是电影的话，详情则是评分，是电影的话，要根据现在更新的集数和总集数进行判断，相等则详情是“XX集全”，否则是“更新至XX集”
        if SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].movie![indexPath.row].episodes == "1" {
            cell.markLabel.text = SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].movie![indexPath.row].rating!
        }else if SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].movie![indexPath.row].nowepisodes == SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].movie![indexPath.row].episodes{
            cell.markLabel.text = SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].movie![indexPath.row].nowepisodes! + "集全"
        }else{
            cell.markLabel.text = "更新至"+SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].movie![indexPath.row].nowepisodes! + "集"
        }
        
        cell.movieNameLabel.text = SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].movie![indexPath.row].name!
        cell.detailLabel.text = SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].movie![indexPath.row].subname!
        
        return cell
    }
    
    /**
     - returns: 返回headview或者footview
     */
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        let headView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "headView", forIndexPath: indexPath)
        //一开始的时候移除headView上的所有子视图，因为headView要重用
        for view in headView.subviews {
            view.removeFromSuperview()
        }
        //设置每个分区的标题
        let title:UILabel = UILabel(frame: CGRectMake(5,0,width/2,30))
        title.text = SHHDataHelper.shareInstance.backrecnameString(indexPath.section)
        headView.addSubview(title)
        headView.backgroundColor = UIColor.whiteColor()
        
        //当vt的值为空的时候，没有更多按钮
        if !(SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].vt == "") {
            //设置分区的  更多  按钮
            let button = UIButton(type: UIButtonType.System)
            button.frame = CGRectMake(width-50,0,50,30)
            button.setTitle("更多>", forState: UIControlState.Normal)
            button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
            headView.addSubview(button)
        }
        
        return headView
    }
    
    
    // #MARK: --UICollectionViewDelegate的代理方法
    /**
    Description:当点击某个Item之后的回应
    */
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("我日")
    }
    
    //#MARK: --UICollectionViewDelegateFlowLayout的代理方法
    /**
    - returns: header的大小
    */
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: width, height: 30)
    }
    /**
     Description:可以定制不同的item
     
     - returns: item的大小
     */
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        
        if SHHDataHelper.shareInstance.titleAndMovieArray[indexPath.section].picsize == "34" {
            return CGSize(width: width/2 - 10, height: 180)
        }else{
            return CGSize(width: width/3 - 10, height: 180)
        }
    }
    
    
    
    
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
